package net.kazed.nextaction.database;

import java.util.HashMap;
import java.util.Map;

import android.database.Cursor;

public class Projection {

   private String[] fieldNames;
   private Map<String, Integer> nameToPosition;
   
   public Projection (String[] fieldNames) {
      this.fieldNames = fieldNames;
      nameToPosition = new HashMap<String, Integer>();
      for (int i = 0; i < fieldNames.length; i++) {
         String name = fieldNames[i];
         nameToPosition.put(name, i);
      }
   }
   
   /**
    * Get Integer value of field.
    * @param cursor Database cursor.
    * @param fieldName Name of field.
    * @return Retrieved value, null if field value is null.
    */
   public Integer getInteger(Cursor cursor, String fieldName) {
      Integer result = null;
      
      int columnIndex = nameToPosition.get(fieldName);
      if (!cursor.isNull(columnIndex)) {
         result = cursor.getInt(columnIndex);
      }
      return result;
   }
   
   /**
    * Get Integer value of field.
    * @param cursor Database cursor.
    * @param fieldName Name of field.
    * @return Retrieved value, null if field value is null.
    */
   public boolean getBoolean(Cursor cursor, String fieldName) {
      boolean result = false;
      
      int columnIndex = nameToPosition.get(fieldName);
      if (!cursor.isNull(columnIndex)) {
         Integer number = cursor.getInt(columnIndex);
         result = (number.intValue() > 0);
      }
      return result;
   }
   
   /**
    * Get String value of field.
    * @param cursor Database cursor.
    * @param fieldName Name of field.
    * @param defaultValue Default value.
    * @return Retrieved value, defaultValue if field value is null.
    */
   public String getString(Cursor cursor, String fieldName, String defaultValue) {
      String result = null;
      
      int columnIndex = nameToPosition.get(fieldName);
      if (!cursor.isNull(columnIndex)) {
         result = cursor.getString(columnIndex);
      } else {
         result = defaultValue;
      }
      return result;
   }

   /**
    * Get String value of field.
    * @param cursor Database cursor.
    * @param fieldName Name of field.
    * @return Retrieved value, null if field value is null.
    */
   public String getString(Cursor cursor, String fieldName) {
      String result = null;
      
      int columnIndex = nameToPosition.get(fieldName);
      if (!cursor.isNull(columnIndex)) {
         result = cursor.getString(columnIndex);
      }
      return result;
   }

   /**
    * @return The fieldNames
    */
   public String[] getFieldNames() {
      return fieldNames;
   }
   
}
